<template>
  <el-drawer
    title="打印按钮"
    :visible.sync="drawer"
    :direction="direction"
    :before-close="handleClose"
    :append-to-body="true"
    size="15%"
  >
    <p class="pButton">
      <el-button
        size="medium"
        type="primary"
        @click="handleClickPrintCurrentPage"
        icon="el-icon-printer"
        >打印当前页</el-button
      >
    </p>
    <p class="pButton">
      <el-button
        size="medium"
        type="primary"
        @click="handlePrintCurrentShare"
        icon="el-icon-printer"
        >打印当前份</el-button
      >
    </p>
    <p class="pButton">
      <el-button
        size="medium"
        type="primary"
        :loading="printClassLoading"
        icon="el-icon-printer"
        @click="handlePrintCurrentClass"
        >打印当前类</el-button
      >
    </p>
    <p class="pButton">
      <el-button
        size="medium"
        type="primary"
        :loading="printAllLoading"
        icon="el-icon-printer"
        @click="handlePrintAll"
        >打印全部</el-button
      >
    </p>
    <!-- 打印当前页 -->
    <printCurrentPage
      ref="printCurrentPage"
      :list="listImg"
      :imgIndex="bigSelectedImageIndex"
    />
    <!-- 打印当前份 -->
    <printCurrentShare ref="myprintbtn" :list="listImg" />
    <!-- 打印全部 + 打印当前类 -->
    <printDocument ref="printDocument" />
  </el-drawer>
</template>

<script>
import printCurrentPage from "./components/printCurrentPage"; //打印当前页
import printCurrentShare from "./components/printCurrentShare"; //打印当前份
import printDocument from "./components/printDocument"; //打印全部
import {
  clickMaterial,
  getImgFromCacheByFlag,
} from "@/api/datacentersg/achives/documentApi";

// 根据给定的树结构和指定的节点id，返回对应的节点对象
const getTreeSelectTreeItem = (tlist, stid) => {
  let obj = undefined;
  const findTreeItem = (list, tid) => {
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (String(tid) === String(item.id)) {
        obj = item;
      }
      if (Array.isArray(item.children) && item.children.length > 0) {
        findTreeItem(item.children, tid);
      }
    }
    return obj;
  };

  findTreeItem(tlist, stid);
  return obj;
};
// 根据给定的树结构，返回所有节点的id数组
const getTreeSelectTreeid = (tree) => {
  let ids = [];
  const getTreeItem = (list) => {
    let obj = {};
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (Array.isArray(item.children) && item.children.length > 0) {
        obj = getTreeItem(item.children);
      } else {
        obj = item;
        ids.push(item);
        continue;
      }
    }
    return obj;
  };
  getTreeItem(JSON.parse(JSON.stringify(tree)));
  return ids;
};

export default {
  components: {
    printCurrentPage,
    printCurrentShare,
    printDocument,
  },
  props: {
    documentName: {
      type: String,
      default: "",
    },
    userId: {
      type: String,
      default: "",
    },
    listImg: {
      type: Array,
      default: () => [],
      required: true,
    },
    selectedImageIndex: {
      type: Number,
    },
    treeData: {
      type: Array,
      default: () => [],
    },
    parentId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      drawer: false,
      direction: "rtl",
      bigSelectedImageIndex: 0,
      printAllLoading: false,
      printClassLoading: false,
    };
  },
  created() {},
  mounted() {
    console.log("treeData", this.treeData);
  },
  methods: {
    init() {
      this.drawer = true;
    },
    // 打印当前页
    handleClickPrintCurrentPage() {
      let refPrint = this.$refs["printCurrentPage"];
      refPrint && refPrint.print();
    },
    //打印当前份
    handlePrintCurrentShare() {
      let refPrint = this.$refs["myprintbtn"];
      refPrint && refPrint.print();
    },
    // 打印当前类
    async handlePrintCurrentClass() {
      let item = getTreeSelectTreeItem(this.treeData, this.parentId);
      let treeList = getTreeSelectTreeid([item]);
      if (!item) {
        return;
      }
      try {
        this.printClassLoading = true;
        let list = await this.getSelectImages(treeList);
        console.log("ss", list);
        let printDocument = this.$refs["printDocument"];
        await printDocument.setPrintImages(list);
        this.printClassLoading = false;
      } catch (error) {
        console.error(error);
        this.printClassLoading = false;
        this.$message.error("打印出错，请重试");
      }
    },
    // 获取打印的图片名字
    async getSelectImages(items) {
      let list = [];
      try {
        for (let i = 0; i < items.length; i++) {
          const item = items[i];
          const params = {
            name: this.documentName,
            idCard: this.userId,
            materialid: item.id, //点击的目录ID
          };
          const res = await clickMaterial(params).catch((err) => {
            console.error(err);
          });
          if (res.code === 0) {
            const resDataList = res.data.res_data;
            console.log("res_data", resDataList);
            if (Array.isArray(resDataList)) {
              for (let j = 0; j < resDataList.length; j++) {
                const imgItem = resDataList[j];
                const paramsNew = {
                  name: this.documentName,
                  idCard: this.userId,
                  fileName: imgItem.fileName, //文件名
                };
                const imgRes = await getImgFromCacheByFlag(paramsNew).catch(
                  (err) => {
                    console.error(err);
                  }
                );
                const [img] = imgRes.data.res_data;
                if (img) {
                  list.push({ id: item.id, name: imgItem.fileName, url: img });
                }
              }
            }
          }
        }
      } catch (error) {
        console.log("error", error);
      }
      return list;
    },
    // 打印全部
    async handlePrintAll() {
      let treeList = getTreeSelectTreeid(this.treeData);
      try {
        this.printAllLoading = true;
        let list = await this.getSelectImages(treeList);
        console.log("ss", list);
        let printDocument = this.$refs["printDocument"];
        await printDocument.setPrintImages(list);
        this.printAllLoading = false;
      } catch (error) {
        console.error(error);
        this.printAllLoading = false;
        this.$message.error("打印出错，请重试");
      }
    },
    handleClose() {
      this.drawer = false;
    },
  },
};
</script>

<style scoped>
.pButton {
  margin-bottom: 10px;
  margin-left: 10px;
}
</style>